package com.example.demo.service.system.impl;

import com.example.demo.dto.system.FieldOptionDTO;
import com.example.demo.dto.system.SubsystemFieldDTO;
import com.example.demo.entity.system.SysFieldOption;
import com.example.demo.entity.system.SysSubsystemField;
import com.example.demo.mapper.system.SysFieldOptionMapper;
import com.example.demo.mapper.system.SysSubsystemFieldMapper;
import com.example.demo.mapper.system.SysUserFieldValueMapper;
import com.example.demo.service.system.SysSubsystemFieldService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 子系统字段服务实现类
 */
@Service
public class SysSubsystemFieldServiceImpl implements SysSubsystemFieldService {

    @Autowired
    private SysSubsystemFieldMapper fieldMapper;
    
    @Autowired
    private SysFieldOptionMapper optionMapper;
    
    @Autowired
    private SysUserFieldValueMapper fieldValueMapper;

    /**
     * 根据系统编码查询字段列表
     *
     * @param systemCode 系统编码
     * @return 字段集合
     */
    @Override
    public List<SysSubsystemField> selectFieldsBySystemCode(String systemCode) {
        return fieldMapper.selectFieldsBySystemCode(systemCode);
    }
    
    /**
     * 根据系统编码查询字段列表（包含选项）
     *
     * @param systemCode 系统编码
     * @return 字段DTO集合
     */
    @Override
    public List<SubsystemFieldDTO> selectFieldsWithOptionsBySystemCode(String systemCode) {
        List<SysSubsystemField> fields = fieldMapper.selectFieldsBySystemCode(systemCode);
        if (fields.isEmpty()) {
            return new ArrayList<>();
        }
        
        List<SubsystemFieldDTO> fieldDTOs = new ArrayList<>();
        for (SysSubsystemField field : fields) {
            SubsystemFieldDTO fieldDTO = new SubsystemFieldDTO();
            BeanUtils.copyProperties(field, fieldDTO);
            
            // 如果是选择类型，查询选项
            if ("select".equals(field.getFieldType()) || "radio".equals(field.getFieldType()) || "checkbox".equals(field.getFieldType())) {
                List<SysFieldOption> options = optionMapper.selectOptionsByFieldId(field.getId());
                if (!options.isEmpty()) {
                    List<FieldOptionDTO> optionDTOs = options.stream().map(option -> {
                        FieldOptionDTO optionDTO = new FieldOptionDTO();
                        BeanUtils.copyProperties(option, optionDTO);
                        return optionDTO;
                    }).collect(Collectors.toList());
                    fieldDTO.setOptions(optionDTOs);
                }
            }
            
            fieldDTOs.add(fieldDTO);
        }
        
        return fieldDTOs;
    }
    
    /**
     * 根据ID查询字段
     *
     * @param fieldId 字段ID
     * @return 字段对象
     */
    @Override
    public SysSubsystemField selectFieldById(Long fieldId) {
        return fieldMapper.selectFieldById(fieldId);
    }
    
    /**
     * 根据ID查询字段（包含选项）
     *
     * @param fieldId 字段ID
     * @return 字段DTO
     */
    @Override
    public SubsystemFieldDTO selectFieldWithOptionsById(Long fieldId) {
        SysSubsystemField field = fieldMapper.selectFieldById(fieldId);
        if (field == null) {
            return null;
        }
        
        SubsystemFieldDTO fieldDTO = new SubsystemFieldDTO();
        BeanUtils.copyProperties(field, fieldDTO);
        
        // 如果是选择类型，查询选项
        if ("select".equals(field.getFieldType()) || "radio".equals(field.getFieldType()) || "checkbox".equals(field.getFieldType())) {
            List<SysFieldOption> options = optionMapper.selectOptionsByFieldId(fieldId);
            if (!options.isEmpty()) {
                List<FieldOptionDTO> optionDTOs = options.stream().map(option -> {
                    FieldOptionDTO optionDTO = new FieldOptionDTO();
                    BeanUtils.copyProperties(option, optionDTO);
                    return optionDTO;
                }).collect(Collectors.toList());
                fieldDTO.setOptions(optionDTOs);
            }
        }
        
        return fieldDTO;
    }
    
    /**
     * 根据系统编码和字段标识查询字段
     *
     * @param systemCode 系统编码
     * @param fieldKey 字段标识
     * @return 字段对象
     */
    @Override
    public SysSubsystemField selectFieldByKey(String systemCode, String fieldKey) {
        return fieldMapper.selectFieldByKey(systemCode, fieldKey);
    }
    
    /**
     * 查询字段列表
     *
     * @param field 字段信息
     * @return 字段集合
     */
    @Override
    public List<SysSubsystemField> selectFieldList(SysSubsystemField field) {
        return fieldMapper.selectFieldList(field);
    }
    
    /**
     * 新增字段
     *
     * @param fieldDTO 字段信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertField(SubsystemFieldDTO fieldDTO) {
        SysSubsystemField field = new SysSubsystemField();
        BeanUtils.copyProperties(fieldDTO, field);
        field.setCreatedAt(new Date());
        
        int rows = fieldMapper.insertField(field);
        if (rows > 0 && fieldDTO.getOptions() != null && !fieldDTO.getOptions().isEmpty()) {
            // 保存选项
            List<SysFieldOption> options = new ArrayList<>();
            for (FieldOptionDTO optionDTO : fieldDTO.getOptions()) {
                SysFieldOption option = new SysFieldOption();
                BeanUtils.copyProperties(optionDTO, option);
                option.setFieldId(field.getId());
                option.setCreatedAt(new Date());
                options.add(option);
            }
            
            optionMapper.batchInsertOptions(options);
        }
        
        return rows;
    }
    
    /**
     * 修改字段
     *
     * @param fieldDTO 字段信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateField(SubsystemFieldDTO fieldDTO) {
        SysSubsystemField field = new SysSubsystemField();
        BeanUtils.copyProperties(fieldDTO, field);
        field.setUpdatedAt(new Date());
        
        int rows = fieldMapper.updateField(field);
        if (rows > 0 && fieldDTO.getOptions() != null && !fieldDTO.getOptions().isEmpty()) {
            // 删除原有选项
            optionMapper.deleteOptionByFieldId(field.getId());
            
            // 保存选项
            List<SysFieldOption> options = new ArrayList<>();
            for (FieldOptionDTO optionDTO : fieldDTO.getOptions()) {
                SysFieldOption option = new SysFieldOption();
                BeanUtils.copyProperties(optionDTO, option);
                option.setFieldId(field.getId());
                option.setCreatedAt(new Date());
                options.add(option);
            }
            
            optionMapper.batchInsertOptions(options);
        }
        
        return rows;
    }
    
    /**
     * 修改字段状态
     *
     * @param fieldId 字段ID
     * @param status 状态
     * @return 结果
     */
    @Override
    public int updateFieldStatus(Long fieldId, Integer status) {
        return fieldMapper.updateFieldStatus(fieldId, status);
    }
    
    /**
     * 删除字段
     *
     * @param fieldId 字段ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteFieldById(Long fieldId) {
        // 删除字段值
        fieldValueMapper.deleteFieldValueByFieldId(fieldId);
        
        // 删除选项
        optionMapper.deleteOptionByFieldId(fieldId);
        
        // 删除字段
        return fieldMapper.deleteFieldById(fieldId);
    }
    
    /**
     * 批量删除字段
     *
     * @param fieldIds 字段ID数组
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteFieldByIds(Long[] fieldIds) {
        int rows = 0;
        for (Long fieldId : fieldIds) {
            // 删除字段值
            fieldValueMapper.deleteFieldValueByFieldId(fieldId);
            
            // 删除选项
            optionMapper.deleteOptionByFieldId(fieldId);
        }
        
        // 删除字段
        return fieldMapper.deleteFieldByIds(fieldIds);
    }
    
    /**
     * 校验字段标识是否唯一
     *
     * @param field 字段信息
     * @return 结果
     */
    @Override
    public boolean checkFieldKeyUnique(SysSubsystemField field) {
        Long fieldId = field.getId() != null ? field.getId() : 0L;
        return fieldMapper.checkFieldKeyUnique(field.getSystemCode(), field.getFieldKey(), fieldId) == 0;
    }
} 